<!--
 *@description:
 *@author: Ming
 *@date: 2021-06-06 17:51:54
 *@version: V1.0.5
-->
<template>
  <div class="collapse">
      <slot></slot>
  </div>
</template>

<script>
import Vue from 'vue'
export default {
  name:'LmCollapse',
  model: {
    prop: 'selected',
    event: 'selectedChange'
  },
  props: {
    selected:{
      type:[String,Number],
      rrequired:true,
      default(){
          return null
      }
    },
    single:{
      type:Boolean,
      default:false
    }
  },

  data() {
    return {
      eventBus:new Vue(),
      selectedArray:[]
    };
  },
  provide(){
    return {
      // this.single?this.eventBus:null
      eventBus:this.eventBus
    }
  },
  mounted () {
    this.selectedArray = this.single?[this.selected]:this.selected
    this.eventBus.$emit("update:selected",this.selected)
    this.eventBus.$on('update:selected',name=>{
      if(!this.single){
        this.selectedArray = name
        this.$emit('selectedChange',name)
        this.$emit('change',name)
        return
      }
      if(this.selectedArray.indexOf(name)<0){
        this.selectedArray.push(name)
      }
      this.$emit('change',this.selectedArray)
    })
    this.eventBus.$on('update:selectedClose',name=>{
      let isIndex = this.selectedArray.indexOf(name)
      if(isIndex>=0 &&  typeof this.selectedArray === 'object'){
        this.selectedArray.splice(isIndex,1)
      }
      this.$emit('change',this.selectedArray)
    })
    this.$children.forEach(vm=>{
      vm.single = this.single
    })
  }
};
</script>

<style scoped>
.collapse{
    border: 1px solid #ddd;
    border-radius: 4px;
    border-bottom: none;
}
</style>
